(function($){
	var currentStep = 1;
	var config = {
		num_tiers:3,
		num_cols: 2
	};
	var selectedTableId, selectedTableData;
	var my_ranks = desigIds;
	var your_ranks = desigIds;
	var tableId = 0;
	
	var tdString ='<input class="amount" name="amount" size="5" placeholder="Amount" id="" value=""/>' +
	'<select class="amount_type" name="amountType">' +
	'<option value="">$ or %</option>' +
	'<option value="fixed_dollar">Fix $</option>' +
	'<option value="fixed_percentage" selected>Fix %</option>' +
	'</select>' +
	'<select class="percentOf" name="percentOf" style="display:none">' +
	'<option value=""></option>' +
	'<option value="gross" selected>Gross Comm</option>' +
	'<option value="earned">Earned Comm</option>' +
	'<option value="agency">Agency Comm</option>' +
	'</select>' +
	'<span class="min_max" style="display:none"><input class="min" name="min" size="5" placeholder="$ Min" id="" value=""/>' +
	'<input class="max" name="max" size="5" placeholder="$ Max" id="" value=""/></span>' +
	'<input type="checkbox" name="usePrevious" /> Use Previous Value';
	
	function initComponents()
	{
		$('#dlg_TierConfig').find('form').get(0).reset();
		$('#dlg_TierConfig').dialog({
			'autoOpen':false,
			'width':600,
			'buttons':{
				'OK': onTableConfigOk,
				'Cancel': onTableConfigCancel
			}
		});
		
	}
	
	function initEventHandlers()
	{
		$('#NumDimension').change(onNumDimensionChange);
		$('#btnNext').click(onBtnNextClick);
		$('#btnBack').click(onBtnBackClick);
		$('#btnSave').click(onBtnSaveClick);
		$('#step2').delegate('.btnTier_config','click',onBtnTableConfigClick);
		$('#step2').delegate('.amount_type', 'change', onAmtTypeChange);
		$('#step2').delegate('input, select', 'change', onFieldChange);
		
	}
	
	function onAmtTypeChange()
	{		
		$(this).closest('td').find('[name="percentOf"]').toggle($(this).val() == 'fixed_percentage');
		$(this).closest('td').find('span.min_max').toggle($(this).val() == 'fixed_percentage');
	}
	function onBtnTableConfigClick()
	{
		$('#dlg_TierConfig').dialog('open');
		$('#dlg_TierConfig').find('form').get(0).reset();
		
		selectedTableId = $(this).closest('table').attr('table_id');
		selectedTableData = structure.tables[selectedTableId];
		
		// populate form
		$.each(selectedTableData, function(key, value) {
			if(key.substr(0,8) == 'compress' || key.substr(0,4) == 'team'){
				if(parseInt(value) == 1){
					$('[name="'+key+'"]').prop('checked',true);
				} else {
					$('[name="'+key+'"]').prop('checked',false);
				}
			}
			$('[name="'+key+'"]').val(value);
		});
	}
	function onBtnNextClick()
	{
		configureTables();
		currentStep++;
		showStep(currentStep);
	
	}
	
	function onTableConfigOk()
	{		
		var currentTableTierNos = $('table[table_id='+selectedTableId+'] tr:gt(1):not([team])').length;
		structure.tables[selectedTableId].numTiers = parseInt($('[name=numTiers]').val());
		if(structure.num_dimension > 0){
			config.num_cols = my_ranks.length;
		}	
		var newTableTierNos = parseInt($('[name=numTiers]').val());
		var tiersToAdd = newTableTierNos - currentTableTierNos;
		
		structure.tables[selectedTableId].numTiers = $('[name=numTiers]').val();
		structure.tables[selectedTableId].eligibility_criteria = $('[name=eligibility]').val();
		
		$('#dlg_TierConfigForm :checkbox').each(function(){
			if($(this).is(':checked')){
				$(this).val('1');
			} else {
				$(this).val('0');
			}
			
		})
		
		structure.tables[selectedTableId].compressionIfIneligible = $('[name=compressionIfIneligible]').val();
		structure.tables[selectedTableId].compressionIfQuitting = $('[name=compressionIfQuitting]').val();
		structure.tables[selectedTableId].compressionIfTierIsNil = $('[name=compressionIfTierIsNil]').val();
		structure.tables[selectedTableId].teamOverride = $('[name=teamOverride]').val();
		
		if(tiersToAdd != 0){
			structure.tables[selectedTableId].numTiers = newTableTierNos;
			if(tiersToAdd > 0){
				addTiers(tiersToAdd, currentTableTierNos);
			}
			if(tiersToAdd < 0){
				var tiersToDel = Math.abs(tiersToAdd);
				deleteTiers(tiersToDel, currentTableTierNos);
			}
		}
		
		if(structure.tables[selectedTableId].teamOverride == 1){
			if($("table[table_id="+selectedTableId+"]").find('tr[team]').length == 0){
				$row=$('<tr/>');
				$row.attr('team', selectedTableId);
				$row.append('<td>Team</td>');
				for(var j=0; j<config.num_cols; j++){
					$row.append('<td column_id="'+ j + '">' + tdString + '</td>');
					structure.tables[selectedTableId].columns[j].team['amountType'] = 'fixed_percentage';
					structure.tables[selectedTableId].columns[j].team['percentOf'] = 'gross';
				}
				$row.appendTo($("table[table_id="+selectedTableId+"]").find('tbody'));
			} 
			else {
				var columns = structure.tables[selectedTableId].columns;
				for(var colId in columns){
					var column = structure.tables[selectedTableId].columns[colId];
					for(var key in column.team){
						structure.tables[selectedTableId].columns[colId].team[key] 
						= $("table[table_id="+selectedTableId+"] tbody").find('tr[team]').find('[column_id="'+colId+'"]').find('[name="'+key+'"]').val();
					}
				}
			}
		} else {
			$("table[table_id="+selectedTableId+"]").find('tr[team]').remove();
			var columns = structure.tables[selectedTableId].columns;
			for(var colId in columns){
				var column = structure.tables[selectedTableId].columns[colId];
				for(var key in column.team){
					structure.tables[selectedTableId].columns[colId].team[key] = '';
				}
			}
		}
		
		showPercentVariables();
		$(this).dialog('close');	
	}
		
	
	function onTableConfigCancel()
	{
		$(this).dialog('close');
		
		selectedTableId = null;
		selectedTableData = null;
	}
	
	function onBtnBackClick()
	{
		//		currentStep--;
		//		showStep(currentStep);
		window.location=window.location=baseUrl + '/structure/summary';
	}
	
	
	function populateTables()
	{
		var tables = structure.tables;
		
		for(var tableId in tables){
			var table = tables[tableId];
			var tblSelector = '[table_id='+tableId+']';
			var $table = $('#tables').find(tblSelector);
			var teamOverride  = table.teamOverride;
			
			for(var colId in table.columns){
				var column = table.columns[colId];
				var colSelector = 'td[column_id='+colId+']';
				var unlimitedColumnVal = column.unlimitedTiers;
				if(parseInt(unlimitedColumnVal) == 1){
					$table.find('tbody tr:first').find(colSelector).find('[name="unlimitedTiers"]').prop('checked',true);
				} else {
					$table.find('tbody tr:first').find(colSelector).find('[name="unlimitedTiers"]').prop('checked',false);
				}
				
				for(var tierId in column.tiers){
					var tier = column.tiers[tierId];
					var tierSelector = 'tr[tier_id='+tierId+']';
					var $tableTier = $table.find(tierSelector);
					var $tableTierColumn = $tableTier.find(colSelector)
					for(var input in tier){
						var inputData = tier[input];						//within the <td>, we find the <input> or <select>
						var inputSelector = '[name='+input+']';
						$tableTierColumn.find(inputSelector).val(inputData);
						if(parseInt(inputData) == 1 && input == 'usePrevious'){
							$tableTierColumn.find(inputSelector).prop('checked',true);
						} else {
							$tableTierColumn.find(inputSelector).prop('checked',false);
						}
					//						if(input == 'amountType'){
					//							$tableTierColumn.find(inputSelector).trigger('change');
					//						}
					}
				}
				
				
				if(teamOverride == 1){
					var teamRowSelector = 'tr[team='+tableId+']';
					var $tableTeamRow = $table.find(teamRowSelector);
					var $tableTeamRowColumn = $tableTeamRow.find(colSelector);
						
					var team = column.team;
					for(var input in team){
						var inputData = team[input];
						var inputSelector = '[name='+input+']';
						$tableTeamRowColumn.find(inputSelector).val(inputData);
						if(parseInt(inputData) == 1 && input == 'usePrevious'){
							$tableTeamRowColumn.find(inputSelector).prop('checked',true);
						} else {
							$tableTeamRowColumn.find(inputSelector).prop('checked',false);
						}
					}
				}
			}
		}
	}
	
	function showPercentVariables()
	{
		$(".amount_type").each(function(){
			if($(this).val() == "fixed_percentage"){
				$(this).closest('td').find('select.percentOf').show();
				$(this).closest('td').find('.min_max').show();
			}
		});
	}
	
	function configureTables()
	{
		var noOfCols;
		var noOfTiers;
		
		if(newStructure == true){
			structure.num_dimension = parseInt($('#NumDimension').val());
			structure.name = $('#structureName').val();
			noOfTiers = parseInt($('#NumTiers').val());
			config.num_tiers = 	noOfTiers;	
			if(structure.num_dimension == 0){
				noOfCols = 1;
			} else {
				noOfCols = desigIds.length;
			}
			structure.numCols = noOfCols;
		} else {
			noOfCols = structure.numCols;
		}
		
		config.num_cols = noOfCols;
		
		if(newStructure == true){
			if(structure.num_dimension == 2){
				for(var i=0; i< desigIds.length; i++){
					//					if(newStructure == false){
					//						var noOfTiers = structure.tables[i].numTiers;
					//					} 
					var tableObj = {
						numTiers: noOfTiers,
						eligibility_criteria: null,
						teamOverride: 0,
						compressionIfIneligible: 0,
						compressionIfQuitting: 0,
						compressionIfTierIsNil: 0,
						columns:[]
					};
					for(var j=0; j< noOfCols; j++ ){
						var columnObj = {
							unlimitedTiers: 0,
							tiers:[],
							team: {
								amount: '', 
								amountType: 'fixed_percentage', 
								percentOf: 'gross', 
								min: '', 
								max: '',
								usePrevious: ''
							}
						};
						tableObj.columns.push(columnObj);
						for(var k=0; k< noOfTiers; k++ ){
							var tierObj = {
								amount: '', 
								amountType: 'fixed_percentage', 
								percentOf: 'gross', 
								min: '', 
								max: '',
								usePrevious: ''
							};
							tableObj.columns[j].tiers.push(tierObj);
						}
					}
					structure.tables.push(tableObj);	
				}
			} else {
				var tableObj = {
					numTiers: noOfTiers,
					eligibility_criteria: null,
					teamOverride: 0,
					compressionIfIneligible: 0,
					compressionIfQuitting: 0,
					compressionIfTierIsNil: 0,
					columns:[]
				};
				for(var i=0; i< noOfCols; i++){
					var columnObj = {
						unlimitedTiers: 0,
						tiers:[],
						team: {
							amount: '', 
							amountType: 'fixed_percentage', 
							percentOf: 'gross', 
							min: '', 
							max: '',
							usePrevious: ''
						}
					};
					tableObj.columns.push(columnObj);
					for(var j=0; j< noOfTiers; j++){
						var tierObj = {
							amount: '', 
							amountType: 'fixed_percentage', 
							percentOf: 'gross', 
							min: '', 
							max: '',
							usePrevious: ''
						};
						tableObj.columns[i].tiers.push(tierObj);
					}
				}
				structure.tables.push(tableObj);
			}
		}
	}
	
	function showStep(stepNum)
	{
		$('.step').hide();
		
		$('#step'+stepNum).show();
		
		if(stepNum == 2 && newStructure == true){
			generateTables();
			showPercentVariables();
		}
		
		if(newStructure == false){
			configureTables();
			generateTables();
			populateTables();
			showPercentVariables();
		}
	}
	
	function onFieldChange() 
	{
		var tableId = $(this).closest('table.table').attr('table_id');
		var tierId = $(this).closest('tr').attr('tier_id');
		var colId = $(this).closest('td').attr('column_id');
		var fieldName =$(this).attr('name');
		
		var teamId = $(this).closest('tr').attr('team');
		
		
		if($(this).is(":checkbox")){
			if($(this).is(":checked")){
				$(this).val('1');
			} else {
				$(this).val('0');
			}
		}
		//alert(teamId);
		
		if($(this).closest('td').hasClass('rank')){
			structure.tables[tableId].columns[colId][fieldName] = $(this).val();
		} else if($(this).closest('tr').is('[team]')){
			structure.tables[tableId].columns[colId].team[fieldName] = $(this).val();
		} else {
			structure.tables[tableId].columns[colId].tiers[tierId][fieldName] = $(this).val();
		}
		
	}
	
	function createTable(tableId)
	{
		tableId = typeof tableId !== 'undefined' ? tableId : 0;
		
		var $table = $('<table></table>');
		var tableLabel = ''
		if(structure.num_dimension == 2){
			tableLabel = 'Closing Agent:<span style="float:right;">' + desigNames[tableId] +'</span>';
		}
		var $thead = $('<thead><tr><th><button class="btnTier_config">Config</button></th><th><b>'+tableLabel+'</b></th></tr></thead>').appendTo($table);
		var $tbody = $('<tbody/>').appendTo($table);
		var $row;
		
		$table.addClass('table')
		.attr('id','table_'+ tableId)
		.attr('table_id', tableId);
		
		var $header = $('<tr><td>Tiers</td></tr>');
		if(structure.num_dimension > 0){
			for(var j=0; j<config.num_cols; j++){
				var rank = desigNames[j];
				if(structure.num_dimension == 1){
					rank = '<b>'+desigNames[j]+'</b>';
				}
				var string = '<td class="rank" column_id="'+j+'">'+rank+'<span style="float:right"><input type="checkbox" name="unlimitedTiers">Unlimited Tiers</span></td>';
				$header.append(string);
			}
		} else {
			var string = '<td class="rank" column_id="0"><span style="float:right"><input type="checkbox" name="unlimitedTiers">Unlimited Tiers</span></td>';
			$header.append(string);
		}
		$header.appendTo($table);
	
		for(var i=0; i<structure.tables[tableId].numTiers; i++){
			$row=$('<tr/>');
			$row.attr('tier_id', i);
			$row.append('<td>Tier '+(i+1)+'</td>');
			for(var j=0; j<config.num_cols; j++){
				$row.append('<td column_id="'+ j + '">' + tdString + '</td>');
			}
			$row.appendTo($table.find('tbody'));
		}
		if(parseInt(structure.tables[tableId].teamOverride) == 1){
			$row=$('<tr/>');
			$row.attr('team', tableId);
			$row.append('<td>Team</td>');
			for(var j=0; j<config.num_cols; j++){
				$row.append('<td column_id="'+ j + '">' + tdString + '</td>');
			}
			$row.appendTo($table.find('tbody'));
		}
		
		$table.find("tr:even").addClass("alt-row");
		$table.appendTo('#tables');
		$('#tables').append('<br/>');
	}
	
	function generateTables()
	{
		if(structure.num_dimension == 2){
			for(var i=0; i<my_ranks.length; i++){
				createTable(i);
			}
		} else {
			createTable(0);
		}
	}
	
	function onNumDimensionChange()
	{
		structure.num_dimension = parseInt($(this).val());
		$('.dimension').hide();
		
		if(structure.num_dimension  > 0){
			for(var i=1; i<=structure.num_dimension; i++){
				$('#dimension'+i).show();
			}
		}
		$('#tiers').show();
	}
	
	function onBtnSaveClick()
	{
		$.post(baseUrl + '/structure/index/'+ structure.id, structure, function(msg){});
		
	}
	
	function addTiers(tiersToAdd, currentTableTierNos)
	{
		for(var i = 0; i < tiersToAdd; i++){
			for(var j=0; j<config.num_cols; j++){
				var tierObj = {
					amount: '', 
					amountType: 'fixed_percentage', 
					percentOf: 'gross', 
					min: '', 
					max: '',
					usePrevious: ''
				};
				structure.tables[selectedTableId].columns[j].tiers.push(tierObj);
			}
				
			$row=$('<tr/>');
			$row.attr('tier_id', (i + currentTableTierNos));
			$row.append('<td>Tier '+(i + 1 + currentTableTierNos)+'</td>');
			for(var j=0; j<config.num_cols; j++){
				$row.append('<td column_id="'+ j + '">' + tdString + '</td>');
			}
			if($("table[table_id="+selectedTableId+"]").find('tr[team]').length == 0){
				$row.appendTo($("table[table_id="+selectedTableId+"]").find('tbody'));
			} else {
				$("table[table_id="+selectedTableId+"] tbody tr[team]").before($row);
			}
			$("table[table_id="+selectedTableId+"]").find("tr:even").addClass("alt-row");
		}
	}
	
	function deleteTiers(tiersToDel, currentTableTierNos)
	{
		for(var i = 0; i < tiersToDel; i++){
			for(var j=0; j<config.num_cols; j++){
				structure.tables[selectedTableId].columns[j].tiers.pop();
			}
			$("table[table_id="+selectedTableId+"]").find('tr[tier_id]:last').remove();
			$("table[table_id="+selectedTableId+"]").find("tr:even").addClass("alt-row");
		}
	}
	
	$(document).ready(function(){
		$('#NumDimension').val('');
		initComponents();
		initEventHandlers();
		if(newStructure == false){
			showStep(2)
		}
	});
})(jQuery);